﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace spring.salesman.data
{
    /// <summary>
    /// 扩展方法，执行存储过程
    /// </summary>
    public partial class SalemanDBEntities
    {
        //泛型方法用于执行标量存储过程
        private T ExecuteFunction<T>(string functionName, System.Data.EntityClient.EntityParameter[] parameters) where T : struct
        {
            System.Data.EntityClient.EntityCommand cmd = ((System.Data.EntityClient.EntityConnection)this.Connection).CreateCommand();
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddRange(parameters);
            cmd.CommandText = this.DefaultContainerName + "." + functionName;
            try
            {
                if (cmd.Connection.State != System.Data.ConnectionState.Open)
                    cmd.Connection.Open();
                var obj = cmd.ExecuteScalar();
                return (T)obj;
            }
            catch (System.Exception)
            {
                throw;
            }
            finally
            {
                cmd.Connection.Close();
            }
        }

        /// <summary>
        /// 执行存储过程得到主键
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public String GetTablePK(string tableName)
        {
            var param = new System.Data.EntityClient.EntityParameter("tableName", System.Data.DbType.String);
            param.Value = tableName;
           
            return ExecuteFunction<int>("sp_GetTablePK", new[] { param }).ToString();
        }
    }
}
